using System;
using System.IO;

namespace Kaleida.ServiceMonitor.Model
{
    public class ScriptSource : IScriptSource
    {
        private string filePath;
        private string name;
        private string originalContent;
        private string content;

        public event EventHandler<EventArgs> ScriptContentChanged;

        public static ScriptSource Load(string filePath, string content)
        {
            return new ScriptSource { FilePath = filePath, OriginalContent = content };
        }

        public static ScriptSource New(string path, string content)
        {
            return new ScriptSource { FilePath = path, originalContent = "", content = content };
        }

        public void Save(IFilesystem filesystem)
        {
            filesystem.WriteAllText(FilePath, Content);
            ResetOriginalContent();
        }

        public string FilePath
        {
            get { return filePath; }
            private set
            {
                filePath = value;
                name = Path.GetFileNameWithoutExtension(value);
            }
        }
        
        public string Name
        {
            get { return name; }
        }

        internal void ResetOriginalContent()
        {
            originalContent = content;
        }

        internal string OriginalContent
        {
            get { return originalContent; }
            private set
            {
                originalContent = value;
                content = value;
            }
        }
        
        public string Content
        {
            get { return content; }
            set
            {
                content = value;

                if (ScriptContentChanged != null)
                    ScriptContentChanged(this, EventArgs.Empty);
            }
        }

        public bool IsDirty
        {
            get { return Content != OriginalContent; }
        }

        public override string ToString()
        {
            return this.GetNameAndEditState();
        }
    }
}